package zhang.test.sqlitedemo.data;

import android.content.Context;
import android.database.sqlite.SQLiteDatabase;
import android.database.sqlite.SQLiteOpenHelper;
import android.util.Log;

/**
 * Created by Administrator on 2017/1/9.
 */

public class DatabaseHelper extends SQLiteOpenHelper {
    // 文本格式
    private static final String TEXT_TYPE = " TEXT";
    private static final String COMMA_SEP = ",";
    // 表名 版本号
    public static final int DATABASE_VERSION = 2;
    public static final String DATABASE_NAME = "FeedReader.db";


    // 创建表
    private static final String SQL_CREATE_ENTRIES =
            "CREATE TABLE " + FeedReaderContract.FeedEntry.TABLE_NAME + " (" +
                    FeedReaderContract.FeedEntry._ID + " INTEGER PRIMARY KEY," +
                    FeedReaderContract.FeedEntry.COLUMN_NAME_TITLE + TEXT_TYPE + COMMA_SEP +
                    FeedReaderContract.FeedEntry.COLUMN_NAME_SUBTITLE + TEXT_TYPE + " )";

    // 删除表
    private static final String SQL_DELETE_ENTRIES =
            "DROP TABLE IF EXISTS " + FeedReaderContract.FeedEntry.TABLE_NAME;
    private static final String TAG = "DatabaseHelper";

    public DatabaseHelper(Context context) {
        super(context, DATABASE_NAME, null, DATABASE_VERSION);

        String dbPath1 = context.getDatabasePath("netpas_sqlite").getPath();

        Log.d(TAG, "DatabaseHelper: 1" + dbPath1);
//        String dbPath2 = context.getDatabasePath("").getPath();
//        Log.d(TAG, "DatabaseHelper: 2" + dbPath2);
    }


    /**
     * 创建表
     *
     * @param db 操作数据库的对象
     */
    @Override
    public void onCreate(SQLiteDatabase db) {
        Log.d(TAG, "onCreate: ");
        db.execSQL(SQL_CREATE_ENTRIES);
    }

    /**
     * 数据库升级的时候使用的方法
     *
     * @param db         操作数据库的对象
     * @param oldVersion 老版本号
     * @param newVersion 新版本号
     */
    @Override
    public void onUpgrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        // 使用for实现跨版本升级数据库
        if (newVersion == 1) {
            Log.d(TAG, "onUpgrade: ");
            db.execSQL("ALTER TABLE entry add column student text");
        }
    }

    // 数据库降级的时候使用
    @Override
    public void onDowngrade(SQLiteDatabase db, int oldVersion, int newVersion) {
        super.onDowngrade(db, oldVersion, newVersion);
    }
}
